<template>
  <div id="searchTask" :catchtouchmove="captcha">
    <scroll-view :style="{'height': height+'px'}" :scroll-y="true" @scrolltolower="fnTask">
      <div class="topBox"></div>
      <div class="header">
        <div class="search">
          <van-search
            v-model="searchInput"
            shape="round"
            placeholder="请输入门店信息"
            @search="onSearch"
            show-action
            background="#FFFFFF"
            custom-class="custom-class"
            field-class="field-class"
            input-class="searchInp"
            cancel-class="searchCal"
            @cancel="onCancel"
          />
        </div>
      </div>
      <div v-if="taskList.records && !taskList.records.length" class="nodata">
        <div>
          <img src="../../../static/imgs/searchnull.png" />
          <p>该门店没有发任何任务哦！请搜索其他店铺～</p>
        </div>
      </div>
      <div class="data_list" v-if="taskList.records && taskList.records.length">
        <div class="data_inner">
          <div class="tab_inner">
            <div class="tab_data">
              <!--每一项-->
              <div class="data_inner_item" v-for="(item,indexs) in taskList.records" :key="indexs">
                <div class="tab_one">
                  <div class="tab_left">
                    <img :src="item.restaurant_logo" alt />
                  </div>
                  <div class="tab_right">
                    <div class="tab_title">
                      {{item.restaurant_name}}
                      <span class="gray">
                        <!-- <formatText :valueData="item.distance" :textType="'distance'" /> -->
                        {{item.distance}}
                      </span>
                    </div>
                    <div class="address">
                      <van-icon name="location-o" />
                      {{item.address}}
                    </div>
                  </div>
                </div>
                <div v-if="item.items.length">
                  <div class="tab_two" v-for="(i,ids) in item.items" :key="ids">
                    <div class="tab_left1">
                      <div></div>
                    </div>
                    <div class="tab_right_two" :class="{'childBorder':ids+1<item.items.length}">
                      <!--进行中任务 且是未结束的任务 有余量按钮 1.高峰期，2.低峰期，3.随时，4.夜宵，5.包夜-->
                      <div class="right_two_title" @click.stop="fnTaskDetail(i.task_id,i.status)">
                        <span>
                          {{i.task_name}}
                          <span v-if="i.task_mold===1">高峰期</span>
                          <span v-if="i.task_mold===2">低峰期</span>
                          <span v-if="i.task_mold===3">随时</span>
                          <span v-if="i.task_mold===4">夜宵</span>
                          <span v-if="i.task_mold===5">包夜</span>
                        </span>
                        <!-- <span v-if="objParam.task_category===2 && i.status===1" class="sum_btn" >余量：{{i.surplus}}</span> -->
                      </div>
                      <div class="money">
                        <div @click.stop="fnTaskDetail(i.task_id,i.status)">
                          <div class="font_logo">奖</div>
                          <div class="money_num">
                            ￥{{i.reward}}
                            <span v-if="i.status===1" class="sum_btn">余量：{{i.surplus}}</span>
                          </div>
                        </div>
                        <!-- items.status	Int	任务状态	0:结束 1:未结束 2:即将进行 -->
                        <!--即将开始任务 显示剩余时间-->
                        <div v-if="i.status===2 && i.countDow" class="sheng_time">
                          剩余时间
                          <br />
                          <van-count-down
                            format="DD天HH:mm:ss"
                            @finish="(i.countDow = 0,i.status = 1)"
                            :time="i.countDow"
                          />
                        </div>
                        <div
                          class="sheng_time"
                          v-if="i.status===2 && !i.countDow"
                          @click.stop="receiverTask(i.status,i)"
                        >
                          <span class="receive">领取</span>
                        </div>
                        <!--进行中任务-->
                        <div
                          v-if="i.status===1&&i.surplus>0"
                          class="sheng_time"
                          @click.stop="receiverTask(i.status,i)"
                        >
                          <span class="receive">领取</span>
                        </div>
                        <div v-else-if="i.status===1" class="sheng_time">
                          <span class="receive ago">已领完</span>
                        </div>
                        <!--过期任务-->
                        <div v-if="i.status===0" class="sheng_time">
                          <span class="receive ago">任务结束</span>
                        </div>
                      </div>
                      <div class="task_time">
                        <span>任务截止：</span>
                        <span class="blue">
                          <formatText :valueData="i.task_end_time" :textType="'time'" />
                        </span>
                      </div>
                    </div>
                    <div style="clear:both;"></div>
                  </div>
                </div>
                <p v-else class="noMoreData">暂无任务</p>
              </div>
              <div v-if="loading">
                <p class="noMoreData">没有更多的数据了</p>
              </div>
              <div style="clear:both;"></div>
            </div>
          </div>
        </div>
      </div>
    </scroll-view>
    <!--弹窗-->
    <ne-captcha
      id="captcha"
      captcha-id="a242c51a9ca04c6b8e578071f190199c"
      width="300px"
      @verify="handlerVerify"
      @close="handlerClose"
    />
    <van-dialog id="van-dialog" />
    <van-popup :show="pShow">
      <notLoginModel @noLogin="pShow = false"></notLoginModel>
    </van-popup>
  </div>
</template>
<script>
import { get } from "../../utils/request";
import Dialog from "../../../static/vant/dialog/dialog";
import formatText from "../../common/components/formatText";
import notLoginModel from "@/common/components/notLoginModel";
export default {
  components: {
    formatText,
    notLoginModel
  },
  data() {
    return {
      searchInput: "",
      // 任务
      taskList: {},
      objParam: {
        tenant_id: "", // 品牌
        restaurant: "", // 门店
        country: "", // 国家ID
        province: "", // 省份ID
        city: "110100", // 城市ID
        address: "", // 地址
        orderType: "1", // 排序：1按距离2按金额 默认：1按距离
        task_category: 0, // 0全部  1即将开始  2进行中  3过期任务
        keyword: "",
        current: 0, // 当前页面
        size: 7 // 每页返回条数
      },
      taskPages: 1,
      height: "",
      status: "", // 接受领取任务参数
      obj: "", // 接受领取任务对象
      isShow: true,
      captcha: false,
      pShow: false,
      isLogin: false,
      isLoad: false, // 是否为重新加载
    };
  },
  onLoad(options) {
    this.isLoad = true;
    this.searchInput = '';
  },
  onShow() {
    this.isLogin = wx.getStorageSync("userInfo").token && true;
    this.fnInitParam();
    // 首页进来不加载列表
    if (!this.isLoad) {
      this.fnTask();
    } else {
      this.taskList = {};
      this.isLoad = false;
    }
    wx.getSystemInfo({
      success: res => {
        this.height = res.windowHeight;
      }
    });
  },
  methods: {
    // 初始化参数
    fnInitParam() {
      this.taskPages = 1;
      this.objParam.current = 0; // 当前页面
      this.objParam.size = 7; // 每页返回条数
    },
    // 领取任务
    receiverTask(status, obj, index, subindex) {
      if (this.isLogin) {
        let _isAuth = wx.getStorageSync("userInfo").auth_status;
        if (_isAuth) {
          this.status = status;
          this.obj = obj;
          this.$root.$mp.page.selectComponent("#captcha").popup();
          this.captcha = true;
        } else {
          Dialog.confirm({
            confirmButtonText: "去实名",
            cancelButtonText: "取消",
            message: "您还未做实名认证，请先完成实名认证"
          })
            .then(res => {
              wx.navigateTo({
                url: "/pages/realName/main"
              });
            })
            .catch(() => { });
        }
      } else {
        this.pShow = true;
      }
    },
    handlerClose() {
      this.$root.$mp.page.selectComponent("#captcha").reset();
      this.captcha = false;
    },
    // 验证码验证结果回调
    handlerVerify: function (ev) {
      // 如果使用了 mpvue，ev.detail 需要换成 ev.mp.detail
      if (!ev.mp.detail[0]) {
        // 验证成功 调用领取任务接口 或者阿里认证页面
        let _isAuth = wx.getStorageSync("userInfo").auth_status;
        if (_isAuth) {
          if (this.status == 1) {
            this.$http
              .post({
                url: "/mobile/api/receivetask",
                data: {
                  customer_id: wx.getStorageSync("userInfo").customer_id,
                  id: this.obj.task_id,
                  lnglat: wx.getStorageSync("lnglat")
                }
              })
              .then(res => {
                if (res.code == "RX0000") {
                  Dialog.alert({
                    confirmButtonText: "确认",
                    message: res.data.msg
                  }).then(() => {
                    this.fnInitParam(); //初始化
                    this.fnTask();
                    this.isShow = false;
                  });
                } else {
                  wx.showToast({
                    icon: "none",
                    title: res.msg
                  });
                  this.isShow = false;
                }
              });
          } else {
            Dialog.alert({
              message: "该任务已被领完，下次早点来哦！☹"
            }).then(() => {
              this.isShow = false;
            });
          }
        } else {
          Dialog.confirm({
            confirmButtonText: "去实名",
            cancelButtonText: "取消",
            message: "您还未做实名认证，请先完成实名认证"
          })
            .then(res => {
              wx.navigateTo({
                url: "/pages/realName/main"
              });
            })
            .catch(() => { });
          this.isShow = false;
        }
      }
    },
    // 任务
    fnTask(refresh) {
      // debugger
      this.objParam.lnglat = wx.getStorageSync("lnglat"); // 经纬度
      if (this.objParam.current >= this.taskPages) {
        return;
      }
      this.objParam.current += 1;
      this.$http
        .post({
          url: "/mobile/api/tasklist",
          data: this.objParam
        })
        .then(res => {
          let that = this;
          if (res.code == "RX0000") {
            let _arr = [];
            for (let val of res.data.records) {
              let _items = [];
              for (let _item of val.items) {
                let _countDow = that.fnCountDown(
                  _item.release_time.replace(/-/g, "/")
                );
                _item.countDow = _countDow;
                _items.push(_item);
              }
              val.distance = this.distanceFun(val.distance);
              val.items = _items;
              _arr.push(val);
            }
            if (this.objParam.current == "1") {
              this.taskList = res.data;
              this.taskList.records = _arr;
            } else {
              this.taskList.current = res.data.current;
              this.taskList.pages = res.data.pages;
              this.taskList.records = this.taskList.records.concat(_arr);
              this.taskList.searchCount = res.data.searchCount;
              this.taskList.size = res.data.size;
              this.taskList.total = res.data.total;
            }
            this.taskPages = res.data.pages;
          } else {
            wx.showToast({
              icon: "none",
              title: res.data
            });
          }
        });
    },
    // 格式化时间戳
    fnCountDown(t) {
      let _sTime = new Date().getTime(); //现在时间（时间戳）
      let _eTime = new Date(t).getTime();
      return _eTime - _sTime > 0 ? _eTime - _sTime : "00:00:00";
    },
    // 任务详情
    fnTaskDetail(id, status) {
      // auth_status
      if (this.isLogin) {
        let _isAuth = wx.getStorageSync("userInfo").auth_status;
        wx.setStorageSync("taskId", id); // 任务id 跳转详情传id
        if (_isAuth) {
          wx.navigateTo({
            url: `/pages/myTaskDetail/main?status=${status}`
          });
        } else {
          Dialog.confirm({
            confirmButtonText: "去实名",
            cancelButtonText: "取消",
            message: "您还未做实名认证，请先完成实名认证"
          })
            .then(res => {
              wx.navigateTo({
                url: "/pages/realName/main"
              });
            })
            .catch(() => { });
        }
      } else {
        this.pShow = true;
      }
    },
    distanceFun(val) { // 距离
      if (val) {
        if (val / 1000 < 1) { // 小于1000米
          return val.toFixed(0) + 'm'
        }
        return (val / 1000).toFixed(2) + 'km';
      } else {
        return '0m'
      }
    },
    onSearch(e) {
      this.objParam.keyword = e.mp.detail;
      this.searchInput = e.mp.detail;
      this.fnInitParam();
      this.fnTask();
    },
    onCancel() {
      this.searchInput = ''
      this.taskList.records = [];
    }
  },
  // 分页
  onReachBottom() {
    this.loading = false;
    if (!this.loading && this.objParam.current <= this.taskList.pages) {
      this.fnTask();
    } else {
      this.loading = true;
    }
  }
};
</script>
<style lang="less">
#searchTask {
  height: 100vh;
  background: rgba(249, 249, 249, 1);
  .topBox {
    height: 6px;
    background: rgba(249, 249, 249, 1);
  }
  .header {
    width: 100%;
    overflow: hidden;
    height: 53px;
    .search {
      width: 100%;
      background: rgba(255, 255, 255, 1);
      /deep/.van-search__content {
        background-color: #ffffff;
      }
    }

    .searchInp {
      background: rgba(255, 255, 255, 1);
      font-size: 12px;
    }
    .field-class {
      height: 32px;
      background: rgba(255, 255, 255, 1);
      box-shadow: 0px 0px 4px 0px rgba(214, 214, 214, 0.5);
      border-radius: 16px;
      padding-left: 8px;
      margin-left: -8px;
    }
    .searchCal {
      font-size: 13px;
    }
  }

  .data_list {
    background: #fff;
    box-sizing: border-box;
    padding: 0 9px;
    .data_inner {
      background: #fff;
      position: relative;
      .van-tab--active {
        color: #226df0;
        font-weight: bolder;
      }
      .tab_inner {
        overflow: hidden;
        .tab_data {
          width: 100%;
          box-sizing: border-box;
          padding-top: 10px;
          .data_inner_item {
            min-height: 90px;
            border-bottom: 10px solid #f9f9f9;
            padding-top: 10px;
            background: #ffffff;
            .tab_one {
              width: 100%;
              clear: both;
              .tab_left {
                width: 69px;
                float: left;
                & > img {
                  display: inline-block;
                  margin: 0 auto;
                  width: 49px;
                  height: 47px;
                  vertical-align: middle;
                  box-shadow: #e6eeec 0px 0px 10px;
                }
              }
              .tab_right {
                float: left;
                height: 64px;
                border-bottom: 1px solid #d8d8d8;
                margin-bottom: 10px;
                width: 78%;
                .tab_title {
                  height: 30px;
                  font-size: 14px;
                  & > .gray {
                    text-align: center;
                    font-size: 8px;
                    display: inline-block;
                    width: 29px;
                    height: 12px;
                    margin-left: 5px;
                    color: #666;
                    background: #f3f3f3;
                  }
                }
                .address {
                  height: 30px;
                  color: #999;
                  font-size: 12px;
                  width: 80%;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  white-space: nowrap;
                }
              }
            }
            .tab_two {
              width: 100%;
              .tab_left1 {
                width: 69px;
                float: left;
                & > div {
                  margin: 0 auto;
                  width: 49px;
                  height: 80px;
                }
              }
              .tab_right_two {
                width: 78%;
                float: left;
                .right_two_title {
                  width: 100%;
                  font-size: 14px;
                  display: flex;
                  align-items: center;
                  justify-content: space-between;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  display: -webkit-box;
                  -webkit-line-clamp: 2;
                  -webkit-box-orient: vertical;
                }
                .money {
                  width: 100%;
                  overflow: hidden;
                  .font_logo {
                    float: left;
                    width: 23px;
                    height: 23px;
                    line-height: 23px;
                    text-align: center;
                    border-radius: 8px 8px 8px 0px;
                    background: #db4a37;
                    font-size: 12px;
                    color: #fff;
                  }
                  .money_num {
                    float: left;
                    width: 55%;
                    height: 25px;
                    line-height: 25px;
                    color: #db4a37;
                    box-sizing: border-box;
                    padding-left: 10px;
                  }
                  .sum_btn {
                    display: inline-block;
                    width: 54px;
                    height: 18px;
                    line-height: 18px;
                    color: #4c46df;
                    font-size: 10px;
                    margin-right: 10%;
                    border-radius: 9px;
                    text-align: center;
                  }
                  .sheng_time {
                    float: left;
                    margin-left: 10px;
                    font-size: 12px;
                    color: #db4a37;
                    text-align: right;
                    .van-count-down {
                      color: #db4a37;
                    }
                    .receive {
                      width: 68px;
                      height: 24px;
                      background: linear-gradient(to right, #4bb0ff, #6149f6);
                      color: #fff;
                      display: flex;
                      align-items: center;
                      justify-content: center;
                      border-radius: 30px;
                      &.ago {
                        background: #ccc;
                      }
                    }
                  }
                }
              }
              .childBorder {
                border-bottom: 1px solid #d8d8d8;
                padding-bottom: 10px;
              }
              .task_time {
                color: #999;
                font-size: 10px;
                display: flex;
                .blue {
                  color: #999999;
                  font-size: 10px;
                }
              }
            }
          }
        }
      }
      .kuai {
        position: absolute;
        top: 45px;
        left: 27px;
        width: 124px;
        height: 50px;
        font-size: 10px;
        overflow: hidden;
        z-index: 7;
        & > div {
          float: left;
          width: 57px;
          height: 20px;
          margin-top: 16px;
          line-height: 20px;
          text-align: center;
          background: #eee;
          color: #999;
          border-radius: 0px 10px 10px 10px;
        }
        .active {
          background: #e0e7fe;
          color: #226df0;
        }
        .juli {
          margin-left: 10px;
        }
      }
    }
  }
  .no_search {
    text-align: center;
    .logo {
      font-size: 40px;
      color: #666;
      margin-top: 75px;
    }
    .no_search_inner {
      width: 100%;
      /*height: 300px;*/
      /*line-height: 300px;*/
      text-align: center;
      background: #fff;
      font-size: 14px;
      color: #666666;
    }
  }
}
.nodata {
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
  height: calc(100% - 100px);
  // margin-top: 150px;
  div {
    margin: auto;
    img {
      width: 176px;
      height: 140px;
    }
    p {
      color: #666666;
      font-size: 14px;
      margin-top: 16px;
    }
  }
}
.noMoreData {
  text-align: center;
  font-size: 30rpx;
  color: #999999;
  padding: 20rpx 0;
}
</style>
